package day01;

import util.JdbcUtil;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Arrays;

@WebServlet("/modify")
public class ModifyEmpServlet extends HttpServlet {

    @Override
    protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {


        request.setCharacterEncoding("utf-8");
        response.setContentType("text/html;charset=utf-8");



        Integer id=Integer.parseInt(request.getParameter("id"));
        String name=request.getParameter("name");
        String salaryStr=request.getParameter("salary");
        Double salary="".equals(salaryStr.trim())
                ?null
                :Double.parseDouble(salaryStr);
        String sex=request.getParameter("sex");
        String edu=request.getParameter("edu");
        String[] hobbies=request.getParameterValues("hobbies");
        String description=request.getParameter("description");


        System.out.println("id = " + id);
        System.out.println("name = " + name);
        System.out.println("salary = " + salary);
        System.out.println("sex = " + sex);
        System.out.println("edu = " + edu);
        System.out.println("hobbies = " + Arrays.toString(hobbies));
        System.out.println("description = " + description);


        Connection con=null;
        PreparedStatement ps=null;

        try{

            con=JdbcUtil.getConnection();

            con.setAutoCommit(false);


            String sql=new StringBuffer()
                    .append("update t_emp ")
                    .append("set name=?, ")
                    .append("    salary=?, ")
                    .append("    sex=?, ")
                    .append("    edu=?, ")
                    .append("    hobbies=?, ")
                    .append("    description=? ")
                    .append("where id=? ")
                    .toString();


            ps=con.prepareStatement(sql);

            ps.setString(1,name);
            ps.setDouble(2,salary);
            ps.setString(3,sex);
            ps.setString(4,edu);
            ps.setString(5,String.join(",",hobbies));
            ps.setString(6,description);
            ps.setInt(7,id);

            ps.executeUpdate();


            con.commit();

        }catch (Exception e){
            e.printStackTrace();
            try {
                con.rollback();
            } catch (SQLException e1) {
                e1.printStackTrace();
            }
        }finally{
            JdbcUtil.close(con,ps,null);
        }

        response.sendRedirect(request.getContextPath()+"/list");

    }
}
